package com.hexb.cloud;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hexb.core.common.ResponseResult;
import com.hexb.core.exception.BusinessException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * @Package : com.feitian.passenger.config
 * @Author : hexb
 * @Date : 2018-08-29 16:36
 * 自定义FeignClient调用错误信息转换
 */
@Configuration
@Slf4j
public class FeignExceptionDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            String responseText = Util.toString(response.body().asReader());
            log.info(String.format("methodKey = %s , Response is : %s", methodKey, responseText));
            ObjectMapper mapper = new ObjectMapper();
            ResponseResult result = mapper.readValue(responseText, ResponseResult.class);
            return new BusinessException(result.getCode() == null ? "feign_error" : result.getCode(),
                    String.format("Call %s Result Is : %s", methodKey, result.getMessage()));
        } catch (IOException e) {
            log.error(String.format("Get Feign Response Error!"), e);
        }
        return null;
    }
}
